<!-- 兑换码生成 -->
<template>
  <div>
    <el-card>
      <div class="topInquire">
        <el-button type="primary" icon="el-icon-circle-plus-outline" size="small" @click="handleAdd">添加礼包码</el-button>

        <div>
          <span>礼包名称：</span>
          <el-input v-model.trim="name" style="width:200px" size="small" clearable placeholder="请输入" />
        </div>
        <div>
          <span>礼包码：</span>
          <el-input v-model.trim="code" style="width:200px" size="small" clearable placeholder="请输入" />
        </div>

        <el-button size="small" type="primary" plain icon="el-icon-search" @click="handleSearch">搜索</el-button>
      </div>

      <!-- 表格 -->
      <div>
        <el-table
          ref="table"
          border
          :data="giftCodeData"
          :header-cell-style="{background:'#f5f7fa'}"
          :height="tableHeight"
        >
          <el-table-column prop="id" label="礼包ID" min-width="120" />
          <el-table-column prop="name" label="礼包名称" min-width="120" />
          <el-table-column prop="code" label="礼包码" min-width="120" />
          <el-table-column prop="type" label="礼包码类型" min-width="120">
            <template slot-scope="scope">
              {{ scope.row.type===1?'共享码':"随机码" }}
            </template>
          </el-table-column>
          <el-table-column prop="rewards" label="奖励" min-width="200" >
            <template slot-scope="scope">
              <span v-for="(item,index) in scope.row.rewards" :key="index">
                {{ item.name }}({{ item.item }})*{{ item.num }}{{ index !== scope.row.rewards.length - 1 ? '，' : '' }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="num" label="生成数量" min-width="100" />
          <el-table-column prop="channel" label="适用渠道" min-width="120" />
          <el-table-column prop="server" label="适用服务器" min-width="120" />
          <el-table-column prop="expireTime" label="过期时间" min-width="120" >
            <template slot-scope="scope">{{ scope.row.expireTime|formatTime }}</template>
          </el-table-column>
          <el-table-column prop="usable" label="是否启用" min-width="120">
            <template slot-scope="scope">
              {{ scope.row.usable?'已启动':"未启用" }}
            </template>
          </el-table-column>
          <!-- <el-table-column prop="userId" label="创建的用户ID" min-width="120" /> -->
          <el-table-column prop="userName" label="创建的用户名称" min-width="120" />
          <!-- <el-table-column prop="useUserId" label="启用的用户ID" min-width="120" /> -->
          <el-table-column prop="useUserName" label="启用的用户名称" min-width="120" />
          <el-table-column label="操作" fixed="right" width="230">
            <template slot-scope="scope">
              <el-button size="small" type="primary" plain icon="el-icon-edit-outline" @click="handleEdit(scope.row)">编辑</el-button>
              <el-button size="small" type="primary" plain icon="el-icon-edit-outline" @click="handleOpenUse(scope.row)">启用</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <el-pagination
          background
          layout="total, prev, pager, next, jumper"
          :total="total"
          :current-page="currentPage"
          :page-size="pageSize"
          @current-change="changePage"
        />
      </div>
    </el-card>

    <!-- 弹窗 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="50%"
      center
      :modal-append-to-body="false"
      @close="closeDialog"
    >
      <el-form ref="ruleForm" :model="formData" label-width="120px" :rules="rules">
        <el-form-item label="礼包名称" prop="name">
              <el-input v-model="formData.name" clearable placeholder="请输入" />
            </el-form-item>
        <el-form-item label="礼包码类型" prop="type">
          <el-select v-model.number="formData.type" size="small" clearable>
            <el-option :value="1" label="共享码" />
            <el-option :value="2" label="独享码" />
          </el-select>
        </el-form-item>
        <el-form-item v-show="formData.type===1?true:false" label="礼包码" prop="code">
          <el-input v-model.trim="formData.code" clearable />
        </el-form-item>
        <el-form-item
          v-show="formData.type===2?true:false"
          label="数量"
          prop="num"
          :rules="[{ type: 'number', message: '数量必须为数字值', trigger: ['blur', 'change']}]"
        >
          <el-input v-model.number="formData.num" clearable />
        </el-form-item>
        <el-form-item label="过期时间" prop="expireTime">
          <el-date-picker
            v-model="formData.expireTime"
            type="datetime"
            placeholder="选择日期时间"
            value-format="timestamp"
            style="width: 100%;"
          />
        </el-form-item>
        <el-form-item label="适用渠道">
          <el-select v-model="formData.channelId" placeholder="请选择渠道" filterable style="width:80%" clearable @change="changeChannelSelect">
            <el-option v-for="item in channelOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="适用服务器" v-show="formData.channelId>0">
          <el-select v-model="formData.serverUid" placeholder="请选择服务器" filterable style="width:80%" clearable>
            <el-option v-for="item in serverByChannelOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="奖励" prop="rewards">
          <el-button style="width:100%" type="primary" plain @click="addRewards">添加</el-button>
          <div v-for="(item,index) in formData.rewards" :key="index" class="props">
            <div style="width:55%">
              <el-form-item
                label="道具"
                :prop="`rewards[${index}].item`"
                :rules="[{ required: true, message: '请输入道具ID', trigger: 'blur' },
                { type: 'number', message: '道具ID为数字值'}]"
                label-width="60px"
                >
                <el-input v-model.number="item.item" size="small" clearable placeholder="请输入道具ID" />
              </el-form-item>
            </div>
            <div style="width:40%">
              <el-form-item
                label="数量"
                :prop="`rewards[${index}].num`"
                :rules="[ { required: true, message: '数量不能为空'},{ type: 'number', message: '数量必须为数字值'}]"
                label-width="60px"
                >
                <el-input v-model.number="item.num" size="small" clearable placeholder="请输入" />
              </el-form-item>
            </div>
            <div style="width:5%">
              <el-button
                type="danger"
                plain
                icon="el-icon-minus"
                circle
                style="padding:1px;margin-left:10px"
                @click="delRewards(index)"
              />
            </div>
          </div>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button size="medium" type="primary" @click="handleConfirm">确 定</el-button>
        <el-button size="medium" @click="closeDialog">取 消</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
import { giftCode, giftCodeSave, giftCodeOpen } from '@/api/giftCode'
import { gameChannelOpt, serverByChannelOpt } from '@/api/aboutOptions'

export default {
  data() {
    return {
      giftCodeData: [],
      total: 0,
      currentPage: 1, // 当前页
      pageSize: 200, // 每页显示条数
      tableHeight: 0, // 表格高度
      dialogVisible: false,
      dialogTitle: '',
      formData: {
        rewards: [], // 奖励
      },
      code: '', // 礼包码
      name: '', // 礼包名称

      channelOptions: [],
      serverByChannelOptions: [],

      rules: {
        name: [{ required: true, message: '请输入礼包名字', trigger: 'blur' }],
        type: [{ required: true, message: '请选择礼包码类型', trigger: 'change' }],
        expireTime: [{ required: true, message: '请选择过期时间', trigger: 'change' }],
      }
    }
  },

  created() {
    this.getGiftCode()
    this.getChannelData()
  },

  mounted() {
    this.$nextTick(() => {
      this.getTableHeight()
    })
    window.addEventListener('resize', this.$debounce(this.getTableHeight, 100))
  },

  beforeDestroy() {
    window.removeEventListener('resize', this.getTableHeight)
  },

  methods: {
    // 获取数据
    async getGiftCode() {
      const res = await giftCode({
        page: this.currentPage,
        limit: this.pageSize
      })
      this.total = res.data.data.count
      this.giftCodeData = res.data.data.data
    },

    // 新增
    async handleAdd() {
      this.dialogTitle = '新增数据'
      await this.getChannelData()
      this.dialogVisible = true
    },

    // 编辑
    async handleEdit(data) {
      this.formData = Object.assign({}, data)
      this.formData.rewards = JSON.parse(JSON.stringify(data.rewards))
      
      if(this.formData.channelId && this.formData.channelId > 0) {
        await this.changeChannelSelect(this.formData.channelId)
      }
      
      this.dialogTitle = '编辑数据'
      this.dialogVisible = true
    },

    async handleOpenUse(data) {
      const res = await giftCodeOpen({id: data.id})
      if (res.data.code === 0) {
        this.$message.success(res.data.message)
      }
      this.getGiftCode()
    },

    // 确认
    async handleConfirm() {
      await this.$refs.ruleForm.validate(async(valid) => {
        if (valid) {
          if (this.formData.num && this.formData.type === 1) {
            delete this.formData.num
          } else if (this.formData.code && this.formData.type === 2) {
            delete this.formData.code
          }
          if(this.formData.channelId === "") {
            this.formData.channelId = 0
          }
          if(this.formData.serverUid === "") {
            this.formData.serverUid = 0
          }
          console.log(JSON.stringify(this.formData))
          if (this.formData.id !== 0) {
            // 编辑
            const updateData = Object.assign({}, this.formData)
            updateData.rewards = JSON.stringify(this.formData.rewards)
            const res = await giftCodeSave(updateData)
            if (res.data.code === 0) {
              this.$message.success(res.data.message)
            }
          } else {
            // 新增
            const rewards = JSON.stringify(this.formData.rewards)
            const addData = { ...this.formData, rewards }
            const res = await giftCodeSave(addData)
            if (res.data.code === 0) {
              this.$message.success(res.data.message)
            }
          }
          this.getGiftCode()
          this.closeDialog()
        }
      })
    },

    // 查询
    async handleSearch() {
      try {
        const query = {}
        if (this.code) {
          query.code = this.code
        }
        if (this.name) {
          query.name = this.name
        }
        query.page = this.currentPage
        query.limit = this.pageSize

        const res = await giftCode(query)
        this.giftCodeData = res.data.data.data
        this.total = res.data.data.count
      } catch (error) {
        console.log(error)
      }
    },

    // 获取渠道
    async getChannelData() {
      const res = await gameChannelOpt()
      this.channelOptions = res.data.data.options
    },

    // 选择渠道
    async changeChannelSelect(val) {
      // 选中渠道后获取服务器
      if (val) {
        const res = await serverByChannelOpt({ channelId: val })
        this.serverByChannelOptions = res.data.data.options
      }
    },


    // 切换页面
    changePage(page) {
      this.currentPage = page
      this.getGiftCode()
    },

    // 关闭弹窗
    closeDialog() {
      this.dialogVisible = false
      this.formData = { rewards: [] }
      this.$refs.ruleForm.clearValidate()// 清空校验
    },

    // 表格自适应高度
    getTableHeight() {
      if (this.$refs.table && this.$refs.table.$el) {
        this.tableHeight = window.innerHeight - this.$refs.table.$el.offsetTop - 170
      } else {
        this.tableHeight = 300
      }
    },

    // 添加奖励
    async addRewards() {
      this.formData.rewards.push({ item: '', num: '' })
    },

    // 删除奖励
    delRewards(index) {
      this.formData.rewards.splice(index, 1)
    },
  }
}
</script>

<style lang="scss" scoped>
.topInquire{
  font-weight: bold;
  font-size: 14px;
  color: #6a7488;
  display: flex;
  flex-wrap: wrap;
  gap: 30px;
}

::v-deep .el-form .el-input__inner{
  border-radius: 0 4px 4px 0;
  height: 40px;
}

::v-deep .el-select{
 width: 100%;
}

.props{
  display: flex;
  width: 100%;
}

.props:not(:last-child) {
  margin-bottom: 15px;
}

::v-deep .props .el-form-item__label{
 background-color: #fff;
 border: none;
 height: none;
}
</style>

